package cn.itcast.bos.service.impl;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.repository.AreaRepository;
import cn.itcast.bos.repository.FixedAreaRepository;
import cn.itcast.bos.repository.OrderRepository;
import cn.itcast.bos.repository.WorkBillRepository;
import cn.itcast.bos.service.OrderService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 * Created by Think on 2017/9/27.
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private FixedAreaRepository fixedAreaRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private WorkBillRepository workBillRepository;
    //注入短信模板
    @Autowired
    @Qualifier(value = "jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    /**下单保存*/
    @Override
    public void save(Order order) {
        // 设置订单号（方案一：客户ID+时间戳生成订单；方案二：使用UUID的方式）
        order.setOrderNum(UUID.randomUUID().toString());
        // 表示下单时间
        order.setOrderTime(new Date());
        // 订单状态 1 待取件 2 运输中 3 已签收 4 异常
        order.setStatus("1"); // 1表示待取件
        //将sendArea和recArea从瞬时态变成持久态(查询出来)
        Area sendArea = order.getSendArea();
        Area persistSendArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
        order.setSendArea(persistSendArea);
        Area recArea = order.getRecArea();
        Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());
        order.setRecArea(persistRecArea);
        /**2.2． 自动分单逻辑1 -- 基于CRM地址完全匹配自动分单*/
        // 使用webservice技术，使用客户下单的地址和客户ID，查询CRM系统，返回定区ID
        // 客户ID
        Integer customerId = order.getCustomer_id();
        //寄件人地址
        String sendAddress = order.getSendAddress();
        //查询地址和客户id对应的定区id
        String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL +
                "/services/customerService/customer/findFixedIdByAddressAndCustomerId?address=" + sendAddress + "&customerId=" + customerId)
                .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .get(String.class);
        if(StringUtils.isNotBlank(fixedAreaId)){
            // 使用定区ID，查询定区
            FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
            // 通过定区对象，获取快递员列表
            Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
            while (iterator.hasNext()){
                System.out.println("自动分单逻辑1...");
                Courier courier = iterator.next();
                saveOrder(order,courier);
                saveWorkBill(order);
                return;
            }
        }

        /**2.3． 自动分单逻辑 -- 基于分区关键字匹配自动分单*/
        // 关键字匹配
        for(SubArea subArea:persistSendArea.getSubareas()){
            // 获取分区对象，使用下单的地址是否包含分区中的关键字
            if(sendAddress.contains(subArea.getKeyWords())){
                Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                while (iterator.hasNext()){
                    System.out.println("自动分单逻辑2...");
                    Courier courier = iterator.next();
                    saveOrder(order,courier);
                    saveWorkBill(order);
                    return;
                }
            }
        }

        // 辅助关键字匹配
        for(SubArea subArea:persistSendArea.getSubareas()){
            // 获取分区对象，使用下单的地址是否包含分区中的辅助关键字
            if(sendAddress.contains(subArea.getAssistKeyWords())){
                Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                while(iterator.hasNext()){
                    System.out.println("自动分单逻辑2...");
                    Courier courier = iterator.next();
                    saveOrder(order,courier);
                    saveWorkBill(order);
                    return; // 不往下执行
                }
            }
        }

        //手工分单
        order.setOrderType("2");
        orderRepository.save(order);
    }



    private void saveOrder(Order order, Courier courier) {
        // 分单类型 1 自动分单 2 人工分单
        order.setOrderType("1");
        //关联订单和客户
        order.setCourier(courier);
        orderRepository.save(order);
    }

    private void saveWorkBill(final Order order){
        WorkBill workBill = new WorkBill();
        workBill.setType("新");
        /*
	 * 新单:没有确认货物状态的
	   已通知:自动下单下发短信
	   已确认:接到短信,回复收信确认信息
	   已取件:已经取件成功,发回确认信息 生成工作单
	 * 已取消:销单
	 *
	 */
        workBill.setPickstate("新单");
        workBill.setBuildtime(new Date());
        workBill.setAttachbilltimes(0);
        workBill.setRemark(order.getRemark());
        final String smsNumber = RandomStringUtils.randomNumeric(4);
        workBill.setSmsNumber(smsNumber);
        workBill.setCourier(order.getCourier());
        workBill.setOrder(order);
        // 工单生成完之后，给快递员发送短信，内容：让快递员去取件
        jmsTemplate.send("bos_couriersms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone", order.getCourier().getTelephone());// 快递员电话（需发送短信）
                mapMessage.setString("code", smsNumber);// 验证码
                return mapMessage;
            }
        });
        workBill.setPickstate("已通知");
        workBillRepository.save(workBill);
    }

    @Override
    public Order findByOrderNum(String orderNum) {
        return orderRepository.findByOrderNum(orderNum);
    }
}
